import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getAppUserInfo } from '@/service/auth/index'
import { cloneDeep } from 'lodash-es'
const initState = { nickname: '', avatarUrl: '' }

export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = ref<IUserInfo>({ ...initState })
    const token = ref(null)
    const setUserInfo = (val: IUserInfo) => {
      userInfo.value = val
    }
    const updateUserInfo = (val: Partial<IUserInfo>) => {
      // 保留未修改字段的深拷贝
      const merged = cloneDeep({
        ...userInfo.value,
        ...val,
      })

      // 执行字段级数据处理
      if (val.phone) {
        merged.phone = val.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
      }

      // 应用更新
      userInfo.value = merged
    }

    const clearUserInfo = () => {
      userInfo.value = { ...initState }
      token.value = null
    }
    // 一般没有reset需求，不需要的可以删除
    const reset = () => {
      userInfo.value = { ...initState }
      token.value = null
    }
    const isLogined = computed(() => !!token.value)
    const getUserInfo = async () => {
      const { code, data } = await getAppUserInfo()
      console.log('用户信息', data)
      if (code === 200) {
        userInfo.value = data
      } else {
        reset()
      }
    }
    const setToken = (tokenVal: string) => {
      token.value = tokenVal
    }

    // 在user store中增加类型转换方法
    return {
      userInfo,
      token,
      setUserInfo,
      clearUserInfo,
      isLogined,
      reset,
      setToken,
      getUserInfo,
      updateUserInfo,
    }
  },
  {
    persist: {
      key: 'userStore',
      paths: ['userInfo', 'token'],
      // 可选：自定义序列化方法
      serializer: {
        serialize: JSON.stringify,
        deserialize: JSON.parse,
      },
    },
  },
)
